package com.songlanyun.modules.gains.service.impl;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.enums.*;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;
import com.songlanyun.common.utils.custom.MathUtils;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.config.model.PointGradeConfigDTO;
import com.songlanyun.modules.config.service.PointGradeConfigService;
import com.songlanyun.modules.gains.dao.ShopOrderGainsDao;
import com.songlanyun.modules.gains.entity.ShopOrderGains;
import com.songlanyun.modules.gains.service.ShopGainsBillService;
import com.songlanyun.modules.gains.service.ShopOrderGainsService;
import com.songlanyun.modules.gainsdonation.entity.ShopOrderGainsDonationEntity;
import com.songlanyun.modules.gainsdonation.service.ShopOrderGainsDonationService;
import com.songlanyun.modules.memberbill.service.SaleRefillCardBillService;
import com.songlanyun.modules.order.entity.ChildOrder;
import com.songlanyun.modules.order.entity.Order;
import com.songlanyun.modules.order.service.ChildOrderService;
import com.songlanyun.modules.pointsexchangeconfig.entity.PointsExchangeConfigEntity;
import com.songlanyun.modules.pointsexchangeconfig.service.PointsExchangeConfigService;
import com.songlanyun.modules.publicbenefitmsg.model.BuyMsg;
import com.songlanyun.modules.publicbenefitmsg.model.to.PublicBenefitMsgTO;
import com.songlanyun.modules.publicbenefitmsg.service.PublicBenefitMsgService;
import com.songlanyun.modules.rights.entity.RightsChildOrder;
import com.songlanyun.modules.rights.entity.RightsOrder;
import com.songlanyun.modules.shop.entity.ShopEntity;
import com.songlanyun.modules.shop.service.ShopService;
import com.songlanyun.modules.usergains.entity.UserOrderGains;
import com.songlanyun.modules.usergains.service.UserBillService;
import com.songlanyun.modules.usergains.service.UserOrderGainsService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.jni.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;


@Service("shopOrderGainsService")
@Slf4j
public class ShopOrderGainsServiceImpl extends ServiceImpl<ShopOrderGainsDao, ShopOrderGains> implements ShopOrderGainsService {


    @Autowired
    private ShopGainsBillService shopGainsBillService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private PointGradeConfigService pointGradeConfigService;


    @Autowired
    private PointsExchangeConfigService pointsExchangeConfigService;

    @Autowired
    private UserBillService userBillService;


    @Autowired
    private UserOrderGainsService userOrderGainsService;

    @Autowired
    private ShopOrderGainsDonationService shopOrderGainsDonationService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private PublicBenefitMsgService publicBenefitMsgService;


    @Autowired
    private SaleRefillCardBillService saleRefillCardBillService;

    @Autowired
    private ChildOrderService childOrderService;

    @Autowired
    private AccountService accountEntityService;



    @Override
    public ShopOrderGains create(ShopOrderGains entity) {

        ValidatorUtils.validateEntity(entity);
        this.baseMapper.insert(entity);
        return entity;
    }

    @Override
    public ShopOrderGains modify(ShopOrderGains entity) {
        ValidatorUtils.validateEntity(entity);
        this.baseMapper.updateById(entity);
        return entity;
    }

    @Override
    public void remove(Long id) {

    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        LambdaQueryWrapper<ShopOrderGains> query = new LambdaQueryWrapper<>();
        query.eq(ShopOrderGains::getShopId, MapUtil.getLong(params, "shop_id"));
        if (params.containsKey("settlement") && StringUtils.isNotBlank(MapUtil.getStr(params, "settlement"))) {
            query.eq(ShopOrderGains::getSettlement, MapUtil.getBool(params, "settlement"));
        }

        if (params.containsKey("order_code") && StringUtils.isNotBlank(MapUtil.getStr(params, "order_code"))) {
            query.like(ShopOrderGains::getOrderCode, MapUtil.getStr(params, "order_code"));
        }

        if (params.containsKey("exists_refund") && StringUtils.isNotBlank(MapUtil.getStr(params, "exists_refund"))) {
            query.eq(ShopOrderGains::getExistsRefund, MapUtil.getBool(params, "exists_refund"));
        }

        if (params.containsKey("child_order_id") && StringUtils.isNotBlank(MapUtil.getStr(params, "child_order_id"))) {
            query.eq(ShopOrderGains::getChildOrderId, MapUtil.getBool(params, "child_order_id"));
        }

        query.orderByDesc(ShopOrderGains::getOrderId).orderByDesc(ShopOrderGains::getCreateTime);

        IPage<ShopOrderGains> page = this.page(
                new Query<ShopOrderGains>().getPage(params),
                query
        );

        page.getRecords().forEach(o->{
            o.loadShopOrderGainsDonation();
            o.loadUserOrderGainsSum();
        });
        return new PageUtils(page);
    }

    /**
     * 订单支付成功记录商家所得
     *
     * @param order
     */
    @Override
    public void initCreate(Order order) {
        if (OrderConstant.PaymentStatus.SUCCESS.equals(order.getPaymentStatus()) && !order.getExchange()) {
            List<ChildOrder> childOrderList = order.getChildOrderList(true);
            for (ChildOrder childOrder : childOrderList) {
                //如果已记录所得不要重复记录
                ShopGainsConstant.GoodsType goodsType = ShopGainsConstant.GoodsType.COMMON_GOODS;
                if(OrderConstant.OrderType.SERVICE_ORDER.equals(order.getOrderType()))
                {
                    goodsType = ShopGainsConstant.GoodsType.SERVICE_GOODS;
                }
                ShopOrderGains obj = this.loadByShopIdAndOrderAndGoodsType(order.getShopId(), order.getId(), childOrder.getId(), goodsType);
                if (obj == null) {
                    BigDecimal oGains = MathUtils.subtractMulti(childOrder.getTotalRealPrice(),
                            childOrder.getFirstOrderReduced(),
                            childOrder.getShopCouponSharing(),
                            childOrder.getPlatformCouponSharing(),
                            childOrder.getPlatformPointZxSharing());

                    ShopOrderGains shopOrderGains = new ShopOrderGains();
                    shopOrderGains.setOrderId(order.getId());
                    shopOrderGains.setOrderCode(order.getOrderCode());
                    shopOrderGains.setChildOrderId(childOrder.getId());

                    shopOrderGains.setGoodsType(goodsType);
                    shopOrderGains.setGoodsId(childOrder.getGoodsId());
                    shopOrderGains.setGoodsTitle(childOrder.getGoodsTitle());


                    shopOrderGains.setShortGoodsTitle(childOrder.getShortGoodsTitle());
                    shopOrderGains.setSkuSetName(childOrder.getSkuSetName());
                    shopOrderGains.setSkuHashCode(childOrder.getSkuHashCode());
                    shopOrderGains.setNumber(childOrder.getNumber());
                    shopOrderGains.setGoodsImg(childOrder.getGoodsImg());
                    shopOrderGains.setRealPrice(childOrder.getRealPrice());
                    shopOrderGains.setTotalRealPrice(childOrder.getTotalRealPrice());
                    shopOrderGains.setSkuBarCode(childOrder.getSkuBarCode());
                    shopOrderGains.setCost(childOrder.getCost());
                    shopOrderGains.setTotalCost(childOrder.getTotalCost());

                    shopOrderGains.setTotalReduced(MathUtils.addMulti(childOrder.getFirstOrderReduced(),
                            childOrder.getShopCouponSharing(),
                            childOrder.getPlatformCouponSharing(),
                            childOrder.getPlatformPointZxSharing()));
                    shopOrderGains.setSalePrice(childOrder.getSalePrice());
                    shopOrderGains.setFirstOrderReduced(childOrder.getFirstOrderReduced());
                    shopOrderGains.setUnit(childOrder.getUnit());
                    shopOrderGains.setShipmentMode(childOrder.getShipmentMode());
                    shopOrderGains.setChannelType(order.getChannelType());
                    shopOrderGains.setProxyGoods(childOrder.getProxyGoods());
                    shopOrderGains.setGiftType(childOrder.getGiftType());
                    shopOrderGains.setSingleGoodsId(childOrder.getSingleGoodsId());
                    shopOrderGains.setMarketingType(order.getMarketingType());
                    shopOrderGains.setShopId(order.getShopId());
                    shopOrderGains.setShopName(order.getShopName());
                    shopOrderGains.setShopName(order.getShopName());
                    shopOrderGains.setGains(oGains);//注意这里是原商品所得（扣除了首单优惠，店铺优惠券分摊，店铺优惠券分摊，平台券分摊）
                    shopOrderGains.setExistsRefund(false);
                    shopOrderGains.setRefundMoney(BigDecimal.ZERO);
                    shopOrderGains.setRightsId(0L);
                    shopOrderGains.setUserId(order.getUserId());
                    shopOrderGains.setSettlement(false);
                    shopOrderGains.setSettlementTime(null);
                    shopOrderGains.setAreaFeature(childOrder.getAreaFeature());
                    shopOrderGains.setConsumptionValue(childOrder.getConsumptionValue());
                    shopOrderGains.setTotalConsumptionValue(childOrder.getTotalConsumptionValue());

                    shopOrderGains.computeAbleGains();
                    this.create(shopOrderGains);
                    System.out.println("创建gains数据成功，类型"+childOrder.getAreaFeature()+",子订单ID"+childOrder.getId());
                    if (childOrder.getGoodsCategoryId() == (long)GoodsConstant.AreaFeature.EXCHANGING.getCode()){
                        continue;
                    }
                    System.out.println("通过订单类型校验");
                    userOrderGainsService.handle(shopOrderGains);

                    this.modify(shopOrderGains);

                    //如果是激活区商品，支付成功后直接分润
                    System.out.println("即将进入激活区商品的判断");
                    if(GoodsConstant.AreaFeature.ACTIVATING.equals(childOrder.getAreaFeature())) {
                        this.settlementByChildOrder(childOrder);

//
//
//                        //判定店长的条件  是否大于10000了
//                        BigDecimal totalPrice = childOrderService.getObtainActivationTotalPrice(childOrder.getUserId());
//
//                        //如果是团长直接跳过
//                        AccountEntity user = accountEntityService.getById(childOrder.getUserId());
//                        //激活人数是否够
//                        Integer allActivatingCount = accountService.getAllActivatingCount(user.getId());
//                        PointGradeConfigDTO config = pointGradeConfigService.info();
//
//                        //直推人数
//                        Integer childActivatingCount = accountService.getChildActivatingCount(user.getId());
//
//                        Path path = Paths.get("/opt/gradelog/gradelog.txt");//追加写模式
//                        try (BufferedWriter writer =
//                                     Files.newBufferedWriter(path,
//                                             StandardCharsets.UTF_8,
//                                             StandardOpenOption.APPEND)){
//                            writer.write("用户id="+user.getId()+"惠途区总金類="+totalPrice+"漖活人数="+allActivatingCount+"直推人数="+childActivatingCount+"订单号="+childOrder.getOrderCode()+"时间="+new Date()+System.lineSeparator());
//                        }catch (Exception e){
//
//                        }
//
//                        if(!(MemberConstant.MemberGrade.GROUP_HEAD.equals(user.getGrade())) && (allActivatingCount >= config.getGeNumPeople()) && (totalPrice.compareTo(new BigDecimal("10000")) > 0)  && (childActivatingCount >= config.getNumDirectReferrals()))
//                        {
//
//                            try (BufferedWriter writer =
//                                         Files.newBufferedWriter(path,
//                                                 StandardCharsets.UTF_8,
//                                                 StandardOpenOption.APPEND)){
//                                writer.write("用户id="+user.getId()+"进入到升级为店长条件中"+"时间="+new Date()+System.lineSeparator());
//                            }catch (Exception e){
//
//                            }
//                            user.setGrade(MemberConstant.MemberGrade.GROUP_HEAD);
//                            accountService.updateById(user);
//                        }


                    }

                }

            }

        }
    }

    public static void main(String[] args) {

        Path path = Paths.get("F:\\test\\test.txt");//追加写模式

        try (BufferedWriter writer =
                     Files.newBufferedWriter(path,
                             StandardCharsets.UTF_8,
                             StandardOpenOption.APPEND)){
            writer.write("用户id=111"+System.lineSeparator());
        }catch (Exception e){

        }
    }


    /**
     * 退款成功后记录到商家所得当中
     *
     * @param rightsOrder
     */
    @Override
    public void refund(RightsOrder rightsOrder) {
        if (RightsOrderConstant.RightsRefundStatus.SUCCESS.equals(rightsOrder.getRightsRefundStatus())) {
            List<RightsChildOrder> rightsChildOrders = rightsOrder.loadRightsChildOrders();
            rightsChildOrders.forEach(rightsChildOrder -> {

                ShopOrderGains obj = this.loadByShopIdAndOrderAndGoodsType(rightsOrder.getShopId(), rightsOrder.getOrderId(), rightsChildOrder.getChildOrderId(), rightsChildOrder.getGoodsType());
                if (obj == null) {
                    log.info(String.format("订单%s,商品【%s】退款成功后，没有找到对应的商家所得记录", rightsOrder.getOrderCode(), rightsChildOrder.getGoodsTitle()));
                } else {
                    if(rightsChildOrder.getRefundMoney().compareTo(obj.getGains())>0)
                    {
                        obj.setRefundMoney(obj.getGains());
                    }
                    else
                    {
                        obj.setRefundMoney(rightsChildOrder.getRefundMoney());
                    }

                    obj.setExistsRefund(true);
                    userOrderGainsService.refundDeduct(obj);
                    obj.computeAbleGains();
                    this.modify(obj);

                    //结算商家所得升级
                    settlementByChildOrder(rightsChildOrder.getChildOrder());
                }
            });
        }
    }

    @Override
    public BigDecimal waitInBill(Long shopId) {
        BigDecimal value = this.baseMapper.waitInBill(shopId);
        return value;
    }

    /**
     * 结算消费商品商家所得
     *
     * @param childOrder
     * @return
     */
    @Override
    public ShopOrderGains settlementByChildOrder(ChildOrder childOrder) {
        ShopGainsConstant.GoodsType goodsType = ShopGainsConstant.GoodsType.COMMON_GOODS;
        if(OrderConstant.OrderType.SERVICE_ORDER.equals(childOrder.getOrderType()))
        {
            goodsType = ShopGainsConstant.GoodsType.SERVICE_GOODS;
        }
        ShopOrderGains obj = this.loadByShopIdAndOrderAndGoodsType(childOrder.getShopId(), childOrder.getOrderId(), childOrder.getId(), goodsType);
        if ((!childOrder.getEnd()) && GoodsConstant.AreaFeature.GENERAL.equals(childOrder.getAreaFeature())) {
            log.info(String.format("订单%s,所购商品【%s】还没有完成不能结算", childOrder.getOrderCode(), childOrder.getGoodsTitle()));
            return obj;
        }

        if (obj.getSettlement()) {
            log.info(String.format("订单%s,所购商品【%s】已结算不要重复结算", childOrder.getOrderCode(), childOrder.getGoodsTitle()));
            return obj;
        }

        if (obj == null) {
            log.info(String.format("订单%s,所购商品【%s】结算商家所得时，没有找到对应的商家所得记录", childOrder.getOrderCode(), childOrder.getGoodsTitle()));
        } else {
            obj.setSettlement(true);
            obj.setSettlementTime(new Date());
            this.modify(obj);

            BigDecimal ableGains = obj.getAbleGains();
            if (ableGains.compareTo(BigDecimal.ZERO) > 0) {
                shopGainsBillService.inBill(childOrder.getShopId(),
                        ShopGainsConstant.InnerMode.SALE_GOODS,
                        ableGains,
                        String.format("订单%s,所购商品【%s】结算商家所得", childOrder.getOrderCode(), childOrder.getGoodsTitle())
                        , childOrder.getOrderCode()
                );
            }

            //会员分佣结算部分===========================================================
            System.out.println("会员分佣结算部分===========================");
            List<UserOrderGains> list = obj.loadUserOrderGainsList(true);
            list.forEach(userOrderGains -> {
                userOrderGains.setSettlement(true);
                userOrderGains.setSettlementTime(new Date());
                userOrderGains.setAbleSettlement(true);
                userOrderGains.setShouldSettlementTime(new Date());
                userOrderGains.setSettlementRemark("系统自动结算");
                userOrderGainsService.modify(userOrderGains);
                if (userOrderGains.getAbleGains().compareTo(BigDecimal.ZERO) > 0) {
                    userBillService.inBill(userOrderGains.getDistributionUserId(),
                            userOrderGains.getEnvRemark(),
                            UserBillConstant.InnerMode.FENRUN_INCOME,
                            userOrderGains.getAbleGains(),
                            userOrderGains.getOrderCode(),"系统");
                }

//                if(GoodsConstant.AreaFeature.ACTIVATING.equals(childOrder.getAreaFeature()))
//                {
//                    saleRefillCardBillService.addBalance(userOrderGains.getDistributionUserId(),
//                            userOrderGains.getBalanceGains(),
//                            userOrderGains.getId().toString(),
//                            BillConstant.InnerMode.BALANCE_GAINS,
//                            BillConstant.InnerMode.BALANCE_GAINS.getMsg()+"之"+userOrderGains.getEnvRemark()
//                            );
//                }

            });
        }

        return obj;
    }


    /**
     * 结算消费商品商家所得
     *
     * @param childOrder
     * @return
     */
    @Override
    public ShopOrderGains settlementServiceGoodsByChildOrder(ChildOrder childOrder) {
        ShopOrderGains obj = this.loadByShopIdAndOrderAndGoodsType(childOrder.getShopId(), childOrder.getOrderId(), childOrder.getId(), ShopGainsConstant.GoodsType.SERVICE_GOODS);
        if (!childOrder.getEnd()) {
            log.info(String.format("订单%s,所购商品【%s】还没有完成不能结算", childOrder.getOrderCode(), childOrder.getGoodsTitle()));
            return obj;
        }

        if (obj.getSettlement()) {
            log.info(String.format("订单%s,所购商品【%s】已结算不要重复结算", childOrder.getOrderCode(), childOrder.getGoodsTitle()));
            return obj;
        }

        if (obj == null) {
            log.info(String.format("订单%s,所购商品【%s】结算商家所得时，没有找到对应的商家所得记录", childOrder.getOrderCode(), childOrder.getGoodsTitle()));
        } else {
            obj.setSettlement(true);
            obj.setSettlementTime(new Date());
            this.modify(obj);

            BigDecimal ableGains = obj.getAbleGains();
            if (ableGains.compareTo(BigDecimal.ZERO) > 0) {
                shopGainsBillService.inBill(childOrder.getShopId(),
                        ShopGainsConstant.InnerMode.SALE_SERVICE,
                        ableGains,
                        String.format("订单%s,所购商品【%s】结算商家所得", childOrder.getOrderCode(), childOrder.getGoodsTitle())
                        , childOrder.getOrderCode()
                );
            }
        }

        return obj;
    }





    @Override
    public ShopOrderGains loadByShopIdAndOrderAndGoodsType(Long shopId, Long orderId, Long childOrderId, ShopGainsConstant.GoodsType goodsType) {
        return this.getOne(new LambdaQueryWrapper<ShopOrderGains>()
                .eq(ShopOrderGains::getShopId, shopId)
                .eq(ShopOrderGains::getOrderId, orderId)
                .eq(ShopOrderGains::getChildOrderId, childOrderId)
                .eq(ShopOrderGains::getGoodsType, goodsType.getCode())
                .last("limit 1")
        );
    }
    @Override
    public void clearOrderGainsData(){
        //查询所有未结算订单
        List<ChildOrder> list = childOrderService.selectNotResultChildOrder();
        System.out.println("子订单数量"+list.size());
        Integer num = 0;
        if(!list.isEmpty()){
            for(ChildOrder order : list){
                this.settlementByChildOrder(order);
//                List<UserOrderGains> gainsList = userOrderGainsService.queryNotResultOrderGains(order.getId());
//                if(!gainsList.isEmpty()){
//                    System.out.println("订单号:"+order.getOrderCode());
//                    num += gainsList.size();
//                }
            }
        }
//        this.settlementByChildOrder(list);
        System.out.println("ok");
        System.out.println("ok");
        System.out.println("ok");
        System.out.println("ok");
        System.out.println("ok");
        System.out.println("ok");
        System.out.println("ok");
        System.out.println("ok");
        System.out.println("ok");
        System.out.println("ok");
//        System.out.println(num);
    }


}
